/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.piaohao.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.piaohao.model.Log;
import org.piaohao.util.string.UUIDGenerator;

/**
 *
 * @author piaohao
 */
public class LogInterceptor implements Interceptor {

    @Override
    public void intercept(ActionInvocation ai) {
        try {
            String actionKey = ai.getActionKey();
            String methodName = ai.getMethodName();
            Controller controller = ai.getController();
            Class<? extends Controller> clazz = controller.getClass();
            if (actionKey.equalsIgnoreCase("/main/login") || actionKey.equalsIgnoreCase("/captcha/get")
                    || actionKey.equalsIgnoreCase("/main/dologin") || actionKey.equalsIgnoreCase("/main/logout")) {
                ai.invoke();
            }
            Field field = clazz.getDeclaredField("moduleName");
            String moduleName = (String) field.get(clazz);
            Log log = new Log();
            log.set("id", UUIDGenerator.getUUID());
            log.set("create_date", new Timestamp(new Date().getTime()));
            log.set("org_id", (String) controller.getSession().getAttribute("orgId"));
            String empName = controller.getSessionAttr("empName");
            if (methodName.equals("add")) {
                log.set("content", "[" + moduleName + "][新增][" + empName + "]");
                log.save();
            } else if (methodName.equals("update")) {
                log.set("content", "[" + moduleName + "][更新][" + empName + "]");
                log.save();
            } else if (methodName.equals("delete")) {
                log.set("content", "[" + moduleName + "][删除][" + empName + "]");
                log.save();
            }
            ai.invoke();
        } catch (NoSuchFieldException ex) {
            Logger.getLogger(LogInterceptor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(LogInterceptor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(LogInterceptor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(LogInterceptor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
